import React, { useEffect, useState, useImperativeHandle } from 'react';
import { Affix, Button, Alert, Radio, Select, Input, Space, Row, Col, Spin } from 'antd';
import { ProCard } from '@ant-design/pro-components';
import request, { exportFile } from '@/utils/request';
import { SettingOutline, DeleteOutlined, EditOutlined } from '@ant-design/icons';
import { CmdbContent, TableColumsProperties, TempImportModal, Authorized } from '@/components';
import cmdbres from '@/data/cmdbres';
import permission from '@/config/permission';
import CreateField from './createField';
import EditField from './editField';
import DeleteField from './deleteField';
import CreateGroup from './createGroup';
import DeleteGroup from './deleteGroup';
import FieldGroupCard from './groupCard';
import DetailModal from './detail';
import './index.less';

const ModelField = ({ history, match, location, moduleId, cRef }) => {
    const [searchLoading, setSearchLoading] = useState(true);
    const [groupData, setGroupData] = useState([]);
    const [allData, setAllData] = useState([]);
    const [showCreateGroup, setShowCreateGroup] = useState(false);
    const [showEditGroup, setShowEditGroup] = useState(false);
    const [showDeleteGroup, setShowDeleteGroup] = useState(false);
    const [showCreateField, setShowCreateField] = useState(false);
    const [showEditField, setShowEditField] = useState(false);
    const [showDeleteModel, setShowDeleteModel] = useState(false);
    const [checkedGroup, setCheckedGroup] = useState(); //选中分组
    const [checkedField, setCheckedField] = useState(); //选中字段
    const [fieldType, setFieldType] = useState();
    const [showDetailModal, setShowDetailModal] = useState(false);

    useEffect(() => {
        if (moduleId) {
            fetchData();
        }
    }, [moduleId]);

    const fetchData = async () => {
        setSearchLoading(true);
        await Promise.all([queryModelPropertyGroup(), queryModelFilelds()]);
        setSearchLoading(false);
    };

    useImperativeHandle(cRef, () => ({
        // changeVal 是暴露给父组件的方法
        changeVal: () => {
            queryModelFilelds();
        },
    }));

    const queryModelPropertyGroup = async () => {
        try {
            let res = await request({
                ...cmdbres.queryModelPropertyGroup(moduleId),
            });
            if (res && res.code == 200) {
                let arr = res.data || [];
                const defaultObj = arr.find((item) => item.propertyGroup == 'default');
                if (!defaultObj) {
                    arr.unshift({
                        propertyGroup: 'default',
                        propertyGroupName: '基本信息',
                    });
                }
                setGroupData(arr);
            } else {
                setGroupData([]);
            }
        } catch (error) {
            setGroupData([]);
            console.log(error);
        }
    };

    const queryModelFilelds = async () => {
        try {
            let res = await request({
                ...cmdbres.queryModelPropertyList,
                data: {
                    queryFilter: {
                        EQ: {
                            cmModuleId: moduleId,
                        },
                    },
                },
            });
            if (res && res.code == 200) {
                setAllData(res.data);
            } else {
                setAllData([]);
            }
        } catch (error) {
            setAllData([]);
            console.log(error);
        }
    };

    const queryModelPropertyType = async () => {
        try {
            let res = await request({
                ...cmdbres.queryModelPropertyType,
                params: {},
            });
            if (res && res.code == 200) {
                let obj = {};
                if (res.data && res.data.length) {
                    res.data.map((item) => (obj[item.name] = item.describe));
                }
                setFieldType(obj);
            }
        } catch (error) {
            setFieldType({});
        }
    };

    useEffect(() => {
        queryModelPropertyType();
    }, []);

    const cardClick = (item) => {
        setCheckedField(item);
        setShowDetailModal(true);
    };

    return (
        <div className="model-field">
            <section className="hcp__card">
                <section className="hcp__card__content" style={{ backgroundColor: '#fff', padding: '10px 15px' }}>
                    {searchLoading ? (
                        <Spin tip="加载中..." style={{ width: '100%' }} />
                    ) : (
                        <>
                            {groupData?.map((item, index) => {
                                const arr = allData
                                    .filter((c) => c.propertyGroup == item.propertyGroup)
                                    ?.sort(function (a, b) {
                                        return a.propertyIndex - b.propertyIndex;
                                    });
                                return (
                                    <FieldGroupCard
                                        key={index}
                                        history={history}
                                        fieldTypeData={fieldType}
                                        groupInfo={item}
                                        cardData={arr}
                                        title={item.propertyGroupName}
                                        showEdit={item.propertyGroup !== 'default'}
                                        showDelete={item.propertyGroup !== 'default'}
                                        showToolip={
                                            item.propertyGroup == 'default' ? '内置模型属性分组不支持修改和删除' : ''
                                        }
                                        setCheckedGroup={setCheckedGroup}
                                        setDeleteGroup={setShowDeleteGroup}
                                        setEditGroup={setShowEditGroup}
                                        cardClick={cardClick}
                                        setCardInfo={setCheckedField}
                                        setCreateCard={setShowCreateField}
                                        setEditCard={setShowEditField}
                                        setDeleteCard={setShowDeleteModel}
                                    ></FieldGroupCard>
                                );
                            })}
                        </>
                    )}
                    <Authorized authority={permission.modelField_add} noMatch={null}>
                        <div
                            onClick={() => {
                                setShowCreateGroup(true);
                            }}
                        >
                            <span className="iconfont icon-plus" style={{ fontSize: 14 }}>
                                &nbsp;添加分组
                            </span>
                        </div>
                    </Authorized>
                </section>
            </section>
            {showCreateGroup && (
                <CreateGroup
                    title="新建信息分组"
                    onCreateFinish={queryModelPropertyGroup}
                    visible={showCreateGroup}
                    setVisible={setShowCreateGroup}
                    moduleId={moduleId}
                />
            )}
            {showEditGroup && (
                <CreateGroup
                    title="编辑信息分组"
                    info={checkedGroup}
                    onCreateFinish={queryModelPropertyGroup}
                    visible={showEditGroup}
                    setVisible={setShowEditGroup}
                    moduleId={moduleId}
                />
            )}
            <DeleteGroup
                onDeleteFinish={queryModelPropertyGroup}
                visible={showDeleteGroup}
                setVisible={setShowDeleteGroup}
                info={checkedGroup}
            />
            <CreateField
                onCreateFinish={queryModelFilelds}
                visible={showCreateField}
                setVisible={setShowCreateField}
                moduleId={moduleId}
                propertyGroup={checkedGroup?.propertyGroup}
            />
            <EditField
                onCreateFinish={queryModelFilelds}
                visible={showEditField}
                setVisible={setShowEditField}
                moduleId={moduleId}
                info={checkedField}
            />
            <DeleteField
                onDeleteFinish={queryModelFilelds}
                visible={showDeleteModel}
                setVisible={setShowDeleteModel}
                info={checkedField}
            />
            <DetailModal
                visible={showDetailModal}
                setVisible={setShowDetailModal}
                info={checkedField}
                fieldType={fieldType}
                setShowEditField={setShowEditField}
            />
        </div>
    );
};

export default ModelField;
